package com.example.sass.jdbc.config.datasource;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.sass.jdbc.entity.SassUserEntity;
import com.example.sass.jdbc.mapper.SassUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class ChangeDataSourceService {

    @Autowired
    private SassUserMapper sassUserMapper;

    @Autowired
    private DynamicRoutingDataSource dynamicRoutingDataSource;

    /**
     * 要切换的 数据库编号
     * @param datasourceNo
     * @return
     */
    public boolean changeDS(String datasourceNo) {
        //切到默认数据源
        DataSourceContextHolder.removeDataSource();
        //找到所有的配置
        List<SassUserEntity> dataSourceList = sassUserMapper.selectList(null);

        if(!CollectionUtils.isEmpty(dataSourceList)){
            for (SassUserEntity dataSource : dataSourceList) {
                if(dataSource.getSassUserNo().equals(datasourceNo)){
                    System.out.println("已找到数据源,dataBase是：" + dataSource.getSassDbName());
                    //判断连接是否存在，不存在就创建
                    dynamicRoutingDataSource.checkCreateDataSource(dataSource);
                    //切换数据源
                    DataSourceContextHolder.setDataSource(datasourceNo);
                    return true;
                }
            }
        }
        return false;
    }
}
